package main

import (
	"fmt"
	"net/http"
	"net/url"
	"os"
)

func myResponse(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("<html><center> <font size=\"20\">Hello！ I am go service started by me!</font></center></html>"))

	fmt.Println("@@@ r.Header()", r.Header)

	// 1. 将 request 中带的 header 写入 response header
	for k := range r.Header {
		w.Header().Set(k, r.Header.Get(k))
	}

	fmt.Println("@@@ w.Header()", w.Header())

	// envs := os.Environ()
	// for _, env := range envs {
	// 	fmt.Println(env)
	// }

	//2. 读取当前系统的环境变量中的 VERSION 配置，并写入 response header
	// fmt.Println("ver:", os.Getenv("GOPROXY"))
	w.Header().Set("GOPROXY", os.Getenv("GOPROXY"))

	fmt.Println("@@@ w.Header()", w.Header())

	// 3. ip:port
	fmt.Println("ip: ", r.Host)

	u, _ := url.Parse("http://www.baidu.com")
	q := u.Query()
	u.RawQuery = q.Encode()
	res, err := http.Get(u.String())
	if err != nil {
		fmt.Println("0")
		return
	}
	resCode := res.StatusCode
	res.Body.Close()
	if err != nil {
		fmt.Println("0")
		return
	}
	fmt.Printf("%d\r\n", resCode)

	fmt.Println("A client has just visited!")
}

/*
	go build -o bin/amd64/httpserver main.go

	docker exec /httpserver
	nsenter -t <pid> -n ip addr

*/
func main() {

	http.HandleFunc("/", myResponse)
	http.ListenAndServe("127.0.0.1:8090", nil)
}
